import Url from "url";
import qs from "qs";
import Cookie from "js-cookie";

/**
 * 解析search字符串 返回query对象
 * @param {string} search url路径的search字符串
 * @param {string|boolean} name string=>返回字段值 boolean=>是否强制重新解析
 * @param {boolean} forceReparse 是否强制重新解析 否时读取缓存
 */
export const parseQuery = (function() {
  let query = {};

  if (localStorage && typeof localStorage.getItem === "function") {
    const cache = localStorage.getItem("parseQuery") || "";
    if (cache) {
      try {
        query = JSON.parse(cache);
      } catch (err) {
        //
      }
    }
  }

  function parseQuery(search, name, forceReparse) {
    if (!search) {
      search = "";
    }

    if (typeof name === "boolean") {
      forceReparse = name;
      name = "";
    }
    forceReparse = !!forceReparse;
    if (query.hasOwnProperty(search) && !forceReparse) {
      return query[search] || {};
    }
    search = search.replace(/^\?/, "");
    const temp = {};
    search
      .split("&")
      // 过滤空字符串
      .filter(item => !!item)
      .forEach(item => {
        let [key, value = ""] = item.split("=");
        temp[key] = decodeURIComponent(value);
      });
    if (name) return temp[name] || "";
    query[search] = temp;
    localStorage &&
      typeof localStorage.setItem === "function" &&
      localStorage.setItem("parseQuery", JSON.stringify(query));
    return temp;
  }

  return parseQuery;
})();

export function addUrlParams(url, params = {}) {
  const parse = Url.parse(url);
  const query = parseQuery(parse.query);
  params = Object.assign({}, query, params);
  const query_string = qs.stringify(params);
  parse.search = `?${query_string}`;
  parse.query = `${query_string}`;
  const url_string = Url.format(parse);
  return url_string;
}

export function mergeRequestUrl(url) {
  const appid = Cookie.get("appid") || "";
  return `/${appid}/${url}`.replace(/\/{1,}/g, "/");
}

export function isDev() {
  return process.env.NODE_ENV === "development";
}

export function isProd() {
  return ["account.presstime.cn", "www.presstime.cn"].includes(
    window.location.host
  );
}
